<template>
  <div class="repair-application">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>后勤报修申请</span>
          <el-button type="primary" @click="showSubmitDialog = true">
            <el-icon><Plus /></el-icon>
            提交维修申请
          </el-button>
        </div>
      </template>

      <!-- 统计信息 -->
      <div class="statistics-section">
        <el-row :gutter="20">
          <el-col :span="4" v-for="stat in statistics" :key="stat.label">
            <div class="stat-card" :class="stat.type">
              <div class="stat-icon">
                <el-icon><component :is="stat.icon" /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select v-model="filterStatus" placeholder="选择状态" style="width: 100%" @change="handleFilter">
              <el-option label="全部状态" value="" />
              <el-option label="待审批" value="待审批" />
              <el-option label="已分配" value="已分配" />
              <el-option label="维修中" value="维修中" />
              <el-option label="完成" value="完成" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filterType" placeholder="选择类型" style="width: 100%" @change="handleFilter">
              <el-option label="全部类型" value="" />
              <el-option 
                v-for="type in repairTypes" 
                :key="type.typeCode" 
                :label="type.typeName" 
                :value="type.typeName" 
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索地点或描述"
              prefix-icon="Search"
              clearable
              @keyup.enter="handleFilter"
            />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 申请列表 -->
      <el-table :data="filteredApplications" style="width: 100%" v-loading="loading">
        <el-table-column prop="applicationNo" label="申请编号" width="150" />
        <el-table-column prop="repairType" label="报修类型" width="120" />
        <el-table-column prop="location" label="报修地点" width="150" />
        <el-table-column prop="description" label="问题描述" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.priority === '紧急' ? 'danger' : 'info'" size="small">
              {{ scope.row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assigneeName" label="维修人员" width="120" />
        <el-table-column prop="createTime" label="申请时间" width="180">
          <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)">查看</el-button>
            <el-button 
              v-if="scope.row.status === '待审批'" 
              size="small" 
              type="warning" 
              @click="editApplication(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="scope.row.status === '待审批'" 
              size="small" 
              type="danger" 
              @click="cancelApplication(scope.row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 提交申请对话框 -->
    <el-dialog
      v-model="showSubmitDialog"
      title="提交维修申请"
      width="600px"
      :before-close="handleCloseSubmitDialog"
    >
      <el-form :model="submitForm" :rules="submitRules" ref="submitFormRef" label-width="100px">
        <el-form-item label="报修类型" prop="repairType">
          <el-select v-model="submitForm.repairType" placeholder="请选择报修类型" style="width: 100%">
            <el-option 
              v-for="type in repairTypes" 
              :key="type.typeCode" 
              :label="type.typeName" 
              :value="type.typeName" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="报修地点" prop="location">
          <el-input v-model="submitForm.location" placeholder="请输入报修地点" />
        </el-form-item>
        
        <el-form-item label="问题描述" prop="description">
          <el-input 
            v-model="submitForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请详细描述问题情况"
          />
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="submitForm.priority">
            <el-radio label="普通">普通</el-radio>
            <el-radio label="紧急">紧急</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="上传照片">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="5"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            accept="image/*"
            list-type="picture-card"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            支持JPG、PNG格式，单张图片不超过5MB，最多上传5张
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSubmitDialog = false">取消</el-button>
          <el-button type="primary" @click="submitApplication" :loading="submitting">
            提交申请
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="维修申请详情"
      width="800px"
    >
      <div v-if="currentApplication" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请编号">{{ currentApplication.applicationNo }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ currentApplication.applicantName }}</el-descriptions-item>
          <el-descriptions-item label="报修类型">{{ currentApplication.repairType }}</el-descriptions-item>
          <el-descriptions-item label="报修地点">{{ currentApplication.location }}</el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="currentApplication.priority === '紧急' ? 'danger' : 'info'">
              {{ currentApplication.priority }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentApplication.status)">
              {{ currentApplication.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDate(currentApplication.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="维修人员">{{ currentApplication.assigneeName || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">{{ currentApplication.description }}</el-descriptions-item>
        </el-descriptions>

        <!-- 照片展示 -->
        <div v-if="currentApplication.photoUrls" class="photo-section">
          <h4>问题照片</h4>
          <div class="photo-grid">
            <div 
              v-for="(photo, index) in currentApplication.photoUrls.split(',')" 
              :key="index"
              class="photo-item"
            >
              <el-image 
                :src="photo" 
                fit="cover"
                :preview-src-list="currentApplication.photoUrls.split(',')"
                :initial-index="index"
              />
            </div>
          </div>
        </div>

        <!-- 状态变更记录 -->
        <div class="status-log-section">
          <h4>状态变更记录</h4>
          <el-timeline>
            <el-timeline-item
              v-for="log in statusLogs"
              :key="log.id"
              :timestamp="formatDate(log.operationTime)"
              :type="getTimelineItemType(log.toStatus)"
            >
              <div class="log-content">
                <div class="log-status">{{ log.toStatus }}</div>
                <div class="log-operator">操作人：{{ log.operatorName }}</div>
                <div class="log-remark" v-if="log.remark">{{ log.remark }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'RepairApplication',
  components: {
    Plus,
    Search
  },
  setup() {
    const loading = ref(false)
    const submitting = ref(false)
    const showSubmitDialog = ref(false)
    const showDetailDialog = ref(false)
    const applications = ref([])
    const repairTypes = ref([])
    const statusLogs = ref([])
    const currentApplication = ref(null)
    
    // 筛选条件
    const filterStatus = ref('')
    const filterType = ref('')
    const searchKeyword = ref('')
    
    // 提交表单
    const submitForm = ref({
      repairType: '',
      location: '',
      description: '',
      priority: '普通'
    })
    
    const submitRules = {
      repairType: [{ required: true, message: '请选择报修类型', trigger: 'change' }],
      location: [{ required: true, message: '请输入报修地点', trigger: 'blur' }],
      description: [{ required: true, message: '请输入问题描述', trigger: 'blur' }]
    }
    
    const submitFormRef = ref()
    const uploadRef = ref()
    const uploadedFiles = ref([])

    // 统计数据
    const statistics = ref([
      { label: '总申请数', value: 0, icon: 'Document', type: 'primary' },
      { label: '待审批', value: 0, icon: 'Clock', type: 'warning' },
      { label: '维修中', value: 0, icon: 'Tools', type: 'info' },
      { label: '已完成', value: 0, icon: 'Check', type: 'success' },
      { label: '已取消', value: 0, icon: 'Close', type: 'danger' },
      { label: '紧急申请', value: 0, icon: 'Warning', type: 'danger' }
    ])

    // 过滤后的申请列表
    const filteredApplications = computed(() => {
      let filtered = applications.value
      
      if (filterStatus.value) {
        filtered = filtered.filter(app => app.status === filterStatus.value)
      }
      
      if (filterType.value) {
        filtered = filtered.filter(app => app.repairType === filterType.value)
      }
      
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        filtered = filtered.filter(app => 
          app.location.toLowerCase().includes(keyword) ||
          app.description.toLowerCase().includes(keyword)
        )
      }
      
      return filtered
    })

    // 获取维修类型列表
    const fetchRepairTypes = async () => {
      try {
        const res = await axios.get('/api/repair/types')
        repairTypes.value = res.data
      } catch (error) {
        console.error('获取维修类型失败', error)
        ElMessage.error('获取维修类型失败')
      }
    }

    // 获取申请列表
    const fetchApplications = async () => {
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      const userId = userInfo.id
      if (!userId) {
        ElMessage.error('请先登录')
        window.location.href = '/login'
        return
      }
      loading.value = true
      try {
        const res = await axios.get(`/api/repair/user/${userId}`)
        applications.value = res.data
      } catch (error) {
        console.error('获取申请列表失败', error)
        ElMessage.error('获取申请列表失败')
      } finally {
        loading.value = false
      }
    }

    // 获取统计信息
    const fetchStatistics = async () => {
      try {
        const res = await axios.get('/api/repair/statistics')
        const stats = res.data
        
        statistics.value[0].value = stats.total || 0
        statistics.value[1].value = stats.pending || 0
        statistics.value[2].value = stats.repairing || 0
        statistics.value[3].value = stats.completed || 0
        statistics.value[4].value = stats.cancelled || 0
        statistics.value[5].value = stats.urgent || 0
      } catch (error) {
        console.error('获取统计信息失败', error)
      }
    }

    // 获取状态变更记录
    const fetchStatusLogs = async (applicationId) => {
      try {
        const res = await axios.get(`/api/repair/${applicationId}/logs`)
        statusLogs.value = res.data
      } catch (error) {
        console.error('获取状态变更记录失败', error)
      }
    }

    // 提交申请
    const submitApplication = async () => {
      try {
        await submitFormRef.value.validate()
        submitting.value = true
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const userId = userInfo.id
        const username = userInfo.username
        const userRole = userInfo.role
        if (!userId) {
          ElMessage.error('请先登录')
          window.location.href = '/login'
          return
        }
        const formData = new FormData()
        formData.append('applicantId', userId)
        formData.append('applicantName', username)
        formData.append('applicantRole', userRole)
        formData.append('repairType', submitForm.value.repairType)
        formData.append('location', submitForm.value.location)
        formData.append('description', submitForm.value.description)
        formData.append('priority', submitForm.value.priority)
        // 添加照片文件
        uploadedFiles.value.forEach(file => {
          formData.append('photos', file.raw)
        })
        const res = await axios.post('/api/repair/submit', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        if (res.data) {
          ElMessage.success('维修申请提交成功')
          showSubmitDialog.value = false
          resetSubmitForm()
          await fetchApplications()
          await fetchStatistics()
        } else {
          ElMessage.error('维修申请提交失败')
        }
      } catch (error) {
        console.error('提交申请失败', error)
        ElMessage.error('提交申请失败')
      } finally {
        submitting.value = false
      }
    }

    // 查看详情
    const viewDetail = async (application) => {
      currentApplication.value = application
      await fetchStatusLogs(application.id)
      showDetailDialog.value = true
    }

    // 编辑申请
    const editApplication = () => {
      // TODO: 实现编辑功能
      ElMessage.info('编辑功能开发中...')
    }

    // 取消申请
    const cancelApplication = async (application) => {
      try {
        const { value: cancelReason } = await ElMessageBox.prompt('请输入取消原因', '取消申请', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (value) => value ? true : '请输入取消原因'
        })
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const userId = userInfo.id
        const username = userInfo.username
        if (!userId) {
          ElMessage.error('请先登录')
          window.location.href = '/login'
          return
        }
        const res = await axios.post(`/api/repair/${application.id}/cancel`, null, {
          params: {
            operatorId: userId,
            operatorName: username,
            cancelReason: cancelReason
          }
        })
        if (res.data) {
          ElMessage.success('申请已取消')
          await fetchApplications()
          await fetchStatistics()
        } else {
          ElMessage.error('取消申请失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消申请失败', error)
          ElMessage.error('取消申请失败')
        }
      }
    }

    // 文件上传处理
    const handleFileChange = (file) => {
      if (!file) {
        ElMessage.error('文件无效，无法上传')
        return false
      }
      // 检查文件大小（5MB）
      if (file.size > 5 * 1024 * 1024) {
        ElMessage.error('文件大小不能超过5MB')
        return false
      }
      uploadedFiles.value.push(file)
    }

    const handleFileRemove = (file) => {
      const index = uploadedFiles.value.findIndex(f => f.uid === file.uid)
      if (index > -1) {
        uploadedFiles.value.splice(index, 1)
      }
    }

    // 筛选处理
    const handleFilter = () => {
      // 筛选逻辑已在computed中实现
    }

    const resetFilter = () => {
      filterStatus.value = ''
      filterType.value = ''
      searchKeyword.value = ''
    }

    // 重置提交表单
    const resetSubmitForm = () => {
      submitForm.value = {
        repairType: '',
        location: '',
        description: '',
        priority: '普通'
      }
      uploadedFiles.value = []
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
    }

    // 关闭提交对话框
    const handleCloseSubmitDialog = () => {
      resetSubmitForm()
      showSubmitDialog.value = false
    }

    // 工具函数
    const getStatusTagType = (status) => {
      const typeMap = {
        '待审批': 'warning',
        '已分配': 'info',
        '维修中': 'primary',
        '完成': 'success',
        '已取消': 'danger'
      }
      return typeMap[status] || 'info'
    }

    const getTimelineItemType = (status) => {
      const typeMap = {
        '待审批': 'warning',
        '已分配': 'info',
        '维修中': 'primary',
        '完成': 'success',
        '已取消': 'danger'
      }
      return typeMap[status] || 'info'
    }

    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      const d = new Date(dateStr)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
    }

    onMounted(() => {
      fetchRepairTypes()
      fetchApplications()
      fetchStatistics()
    })

    return {
      loading,
      submitting,
      showSubmitDialog,
      showDetailDialog,
      applications,
      repairTypes,
      statusLogs,
      currentApplication,
      filterStatus,
      filterType,
      searchKeyword,
      submitForm,
      submitRules,
      submitFormRef,
      uploadRef,
      uploadedFiles,
      statistics,
      filteredApplications,
      submitApplication,
      viewDetail,
      editApplication,
      cancelApplication,
      handleFileChange,
      handleFileRemove,
      handleFilter,
      resetFilter,
      handleCloseSubmitDialog,
      getStatusTagType,
      getTimelineItemType,
      formatDate
    }
  }
}
</script>

<style scoped>
.repair-application {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistics-section {
  margin-bottom: 30px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-card.primary {
  border-left: 4px solid #409eff;
}

.stat-card.warning {
  border-left: 4px solid #e6a23c;
}

.stat-card.info {
  border-left: 4px solid #909399;
}

.stat-card.success {
  border-left: 4px solid #67c23a;
}

.stat-card.danger {
  border-left: 4px solid #f56c6c;
}

.stat-icon {
  margin-right: 15px;
  font-size: 24px;
  color: #409eff;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.photo-section {
  margin-top: 20px;
}

.photo-section h4 {
  margin-bottom: 15px;
  color: #303133;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
}

.photo-item {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.photo-item .el-image {
  width: 100%;
  height: 150px;
}

.status-log-section {
  margin-top: 30px;
}

.status-log-section h4 {
  margin-bottom: 15px;
  color: #303133;
}

.log-content {
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
}

.log-status {
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.log-operator {
  font-size: 12px;
  color: #606266;
  margin-bottom: 3px;
}

.log-remark {
  font-size: 12px;
  color: #909399;
  font-style: italic;
}
</style> 